import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应格式
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        //1.从请求中获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username == null || username.equals("") || password == null || password.equals("")) {
            resp.setStatus(403);
            resp.getWriter().write("用户名或密码不能为空！");
            return;
        }
        //2.根据用户名从数据库中拿出对应密码
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if(user == null) { //用户名是乱写的
            resp.setStatus(403);
            resp.getWriter().write("用户名或密码错误！");
            return;
        }
        //3.检验密码是否正确
        if(!password.equals(user.getPassword())) {
            resp.setStatus(403);
            resp.getWriter().write("用户名或密码错误！");
            return;
        }
        //4.创建session会话，保存信息
        HttpSession session = req.getSession();
        session.setAttribute("user", user);
        //5.重定向到博客列表页
        resp.sendRedirect("blog_list.html");
    }

    //检测是否登录
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应格式
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        //1.获取session对象
        HttpSession session = req.getSession();
        if(session == null) {
            resp.setStatus(403);
            return;
        }
        //2.获取user对象
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            return;
        }
        //登录了，就什么事都不干
        resp.setStatus(200);
    }
}
